<template>
	<el-row class="contont" v-if="dataMap">
		<!-- <el-col :span="2" class="button" :offset="1">
			<el-button plain>
				<i class="el-icon-guide"></i>
				地图
			</el-button>
		</el-col> -->
		<el-col :span="2" class="button">
			<el-button plain :class="type == '2' ? 'active' : ''" @click="switchType(2)">
				<i class="el-icon-data-line"></i>
				数据图
			</el-button>
		</el-col>
<!-- 		<el-col :span="2" class="button">
			<el-button plain :class="type == '1' ? 'active' : ''" @click="switchType(1)">
				<i class="el-icon-data-analysis"></i>
				柱状图
			</el-button>
		</el-col> -->
		<el-col :span="2" class="button">
			<el-button plain :class="type == '4' ? 'active' : ''" @click="switchType(4)">
				<i class="el-icon-notebook-2"></i>
				数据列表
			</el-button>
		</el-col>

		<el-col :span="2" v-if="areaList.length > 0 && areaList[0].children == undefined " class="choice">
			<el-select multiple collapse-tags   v-model="area" placeholder="请选择地区" class="dropdown" @change="changeSelect(1)">
				<el-option v-for="(item,index) in areaList" :key="item" :label="item" :value="item">
				</el-option>
			</el-select>
		</el-col>
    <el-col :span="2" v-if="areaList.length > 0 && areaList[0].children != undefined " class="choice">
      <el-cascader
      class="dropdown"
        v-model="area"
        :props="props"
        :options="areaList"
        collapse-tags
        @change="changeSelect(1)"></el-cascader>
<!--    	<el-select multiple   v-model="area" placeholder="请选择地区" class="dropdown" @change="changeSelect(1)">
    		<el-option v-for="(item,index) in areaList" :key="item" :label="item" :value="item">
    		</el-option>
    	</el-select> -->
    </el-col>
		<el-col :span="2" v-if="targetList.length > 0" class="choice">
			<el-select multiple collapse-tags  v-model="target" placeholder="请选择指标" class="dropdown" @change="changeSelect(2)">
				<el-option v-for="(item,index) in targetList" :key="item" :label="item" :value="item">
				</el-option>
			</el-select>
		</el-col>
		<el-col :span="2" v-if="typeList.length > 0" class="choice">
			<el-select multiple collapse-tags  v-model="description" placeholder="请选择类型" class="dropdown" @change="changeSelect(3)">
				<el-option v-for="(item,index) in typeList" :key="item" :label="item" :value="item">
				</el-option>
			</el-select>
		</el-col>

		<el-col :span="3" :offset="Object.keys(this.dataMap).length > 0 ? Object.keys(this.dataMap).length == 1 ? 8 : 6 : 10 ">
			<el-date-picker class="datePicker" v-model="time" type="daterange" align="right" unlink-panels
				range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"
				value-format="yyyy-MM-dd" @change="getDataList()">
			</el-date-picker>
			<!-- 			<el-date-picker v-model="value1" type="date" placeholder="选择日期时间" class="datePicker">
			</el-date-picker> -->
		</el-col>
		<el-col :span="2" v-if="type != 4">
			<a href="javascript:void(0);">
				<span class="spans" @click="es_charts()">
					<i class="el-icon-picture"></i>PNG
				</span>
			</a>

		</el-col>
		<el-col :span="2" v-if="type == 4">
			<span class="spans" @click="handleExportXls()">
				<i class="el-icon-s-marketing"></i>XLS
			</span>
		</el-col>
		<el-col :span="24" class="charts">
      <span v-if="type != 4">
        <span v-if="echarts != null && echarts.length > 0">
          <brokenline ref="brokenline" v-if="type == '2'"></brokenline>
          <histogram ref="histogram" v-if="type == '1'"></histogram>
        </span>
        <el-col :span="24" class="blank" v-else>
          无数据
        </el-col>
      </span>

        <dataTable ref="dataTable" v-else></dataTable>
		</el-col>

	</el-row>
</template>

<script>
	import histogram from '@/view/compents/graphic/histogram'
	import brokenline from '@/view/compents/graphic/brokenline'
	import dataTable from '@/view/compents/graphic/table'
	export default {
		components: {
			histogram,
			brokenline,
			dataTable
		},

		data() {
			return {
        props: { multiple: true },
				type: '2',
				area: '',
				areaList: [],
				target: '',
				targetList: [],
				description: '',
				typeList: [],
        class_name:'',
        classList:[],
				dataList: [],
				kindId: '',
				programId: '',
				dataMap: null,
        startTime:null,
        endTime:null,
        echarts:[],
        select:1,
				pickerOptions: {
					shortcuts: [{
						text: '最近一周',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近一个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近三个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
							picker.$emit('pick', [start, end]);
						}
					}]
				},
				time: '',
				url: {
					getChoiceList: "/web/program/getChoiceList",
					getEcharts: "/web/program/getEcharts",
          exportXlsUrl: "/web/program/exportXls"
				},
			}
		},
		created() {

		},
		watch: {
			$route(to, from) {
				console.log('跳转成功')
				if (to.query.kindId || to.query.programId) {
					this.kindId = to.query.kindId
					this.programId = to.query.programId
					if (this.kindId || this.programId) {
            this.echarts = []
						this.areaList = []
						this.area = ''
						this.targetList = []
						this.target = ''
						this.typeList = []
						this.description = ''
            this.classList = []
            this.class_name = ''


					}
					this.getChoiceList()
				}
			},
			value1(n, o) {
				//每次更改都会触发当前方法
				console.log(n)
			}
		},
		methods: {
      /**
       * 下载excel
       */
      async handleExportXls(fileName){
        if (!fileName || typeof fileName !== 'string') {
          fileName = '导出文件'
        }
        let param = {}
        if (this.target.length > 0) {
        	param.target = this.target
        }
        if (this.area.length > 0) {
        	param.area = this.area
        }
        if (this.description.length > 0) {
        	param.type = this.description
        }
        let params = {
        	"kindId": this.kindId,
        	"param": param,
        	"programId": this.programId,
        	"type": 1
        }
        if (this.time) {
        	params.startTime = this.time[0]
        	params.endTime = this.time[1]
        }
        await this.$http.postBlob(this.url.exportXlsUrl, params).then((data) => {
          console.log(data)
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' }), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) // 下载完成移除元素
            window.URL.revokeObjectURL(url) // 释放掉blob对象
          }
        });
      },
			/*
				图表转化成图片并下载的方法
			*/
			es_charts() {
				let base_64 = document.getElementById('main').getElementsByTagName('canvas')[0];
				let width = base_64.width;
				let height = base_64.height;
				let ctx = base_64.getContext('2d');
				ctx.drawImage(base_64, width, height);
				let url = base_64.toDataURL();
				let aLink = document.createElement('a');
				let evt = document.createEvent('HTMLEvents');
				aLink.download = new Date().getTime();
				aLink.href = url;
				aLink.click();
			},
			async getChoiceList(kindId, programId) {
				let res = await this.$http.post(this.url.getChoiceList, {
					kindId: this.kindId,
					programId: this.programId
				});
				if (res.data.code == 200) {
					this.dataMap = res.data.result
					for (let item in this.dataMap) {
						if (item == 'area') {
							this.areaList = this.dataMap[item]
              if(this.areaList[0].children != undefined){
                this.area = [[this.areaList[0].value,this.areaList[0].children[0].value]]
              }else{
                this.area = [this.areaList[0]]
              }
              this.select = 1
						}
						if (item == 'target') {
							this.targetList = this.dataMap[item]
							this.target = [this.targetList[0]]
              this.select = 2
						}
						if (item == 'type') {
							this.typeList = this.dataMap[item]
							this.description = [this.typeList[0]]
              this.select = 3
						}
					}
					this.getDataList()
				} else {
					this.$message.warning(res.data.message)
				}

			},
			switchType(type) {
				this.type = type;
				this.changeSelect(this.select)
			},
      changeSelect(select){
        this.select = select
        this.echarts = []
        if(select == 1 && this.area.length == 0){
          return
        }
        if(select == 2 && this.target.length == 0){
          return
        }
        if(select == 3 && this.description.length == 0){
          return
        }
        if(this.area.length > 1 && this.description.length > 1){
          if(select == 1){
            this.area.pop(this.area[this.area.length])
          }
          if(select == 3){
            this.description.pop(this.description[this.description.length])
          }
          this.$message.warning("仅支持单个筛选条件多种查询")
        }
        if(this.target.length > 1 && this.area.length > 1){
          if(select == 1){
            this.area.pop(this.area[this.area.length])
          }
          if(select == 2){
            this.target.pop(this.target[this.target.length])
          }
          this.$message.warning("仅支持单个筛选条件多种查询")
        }
        if(this.target.length > 1 && this.description.length > 1){
          if(select == 2){
            this.target.pop(this.target[this.target.length])
          }
          if(select == 3){
            this.description.pop(this.description[this.description.length])
          }
          this.$message.warning("仅支持单个筛选条件多种查询")
        }
        if(select == 2){
          if(this.type != 4){
            if(this.target.length > 1){
              for(let value in this.target){
                this.getDataList(this.target[value],2)
              }
            }else{
              this.getDataList()
            }
          }else{
            this.getTableList()
          }
        }
        if(select == 1){
          if(this.type != 4){
            if(this.area.length > 1){
              for(let value in this.area){
                this.getDataList(this.area[value],1)
              }
            }else{
              this.getDataList()
            }
          }else{
            this.getTableList()
          }

        }
        if(select == 3){
          if(this.type != 4){
            if(this.description.length > 1){
              for(let value in this.description){
                this.getDataList(this.description[value],3),1000
              }
            }else{
              this.getDataList()
            }
          }else{
            this.getTableList()
          }
        }

      },
      async getTableList() {
        let param = {}
        if (this.target.length > 0) {
        	param.target = this.target;
        }
        if (this.area.length > 0) {
        	param.area = this.area;
        }
        if (this.description.length > 0) {
        	param.type = this.description;
        }
        let params = {
        	"kindId": this.kindId,
        	"param": param,
        	"programId": this.programId,
        	"type": this.type
        }
        this.$nextTick(() => {
        	this.$refs.dataTable.getPage(params,this.select);
        })
      },
      /**
       * 获取图表数据
       */
			async getDataList(value,type) {
				let param = {}
				if (this.target.length > 0) {
					param.target = this.target.join(",");
				}
        if(type == 2){
          param.target = value
        }
				if (this.area.length > 0) {
          if((typeof this.area[0]) == 'string'){
            param.area = this.area.join("/");
          }else{
            param.area = this.area[0].join("/");
          }

				}
        if(type == 1){
          if((typeof this.area[0]) == 'string'){
            param.area = value;
          }else{
            param.area = value.join("/");
          }
        }
         console.log(param.area)
				if (this.description.length > 0) {
					param.type = this.description.join(",");
				}
        if(type == 3){
          param.type = value
        }
        if(Object.keys(param).length==0){
          return
        }
				let params = {
					"kindId": this.kindId,
					"param": param,
					"programId": this.programId,
					"type": this.type
				}
				if (this.time) {
					params.startTime = this.time[0]
					params.endTime = this.time[1]
				}else{
         if(this.startTime != null && this.endTime != null){
           params.startTime = this.time[0]
           params.endTime = this.time[1]
         }
        }
				if (this.type != 4) {
          this.getEcharts(params,type)
				}
			},
      async getEcharts(params,type){
        let res = await this.$http.post(this.url.getEcharts, params);
        if (res.data.code == 200) {
        	this.dataList = res.data.result
          if(this.dataList != null){
            this.dataList.reverse()
            this.echarts.push(this.dataList)
            if(this.startTime == null && this.endTime == null){
              this.startTime = this.dataList[0].year_date
              this.endTime = this.dataList[this.dataList.length - 1].year_date
            }
          }
          if(this.echarts && this.echarts.length > 0){
            if (this.type == 2) {
              this.$nextTick(() => {
                this.$refs.brokenline.drawLine(this.echarts,type);
              })
            }
            if (this.type == 1) {
              this.$nextTick(() => {
                this.$refs.histogram.drawLine(this.echarts,type);
              })
            }
          }
        } else {
        	this.$message.warning(res.data.message)
        }
      }
		}
	}
</script>

<style lang="scss">
  // .el-select-dropdown{
  //         max-width: 243px;
  //     }
  //     .el-select-dropdown__item{
  //         display: inline-block;
  //     }
  //     .el-select-dropdown__item span {
  //         min-width: 205px;
  //         display: inline-block;
  //    }
  .blank{
  	width: 100%;
  	height: 85vh;
  	padding-top: 4vh;
    margin-top: 2vh;
    padding-left: 2%;
    border-radius: 7px;
    background-color: #ffffff;
  }
	.charts {
		background-color: #ffffff;
		margin-top: 2vh;
    height: 85vh;
		border-radius: 7px;
	}

	.choice {
		margin-left: 0.625rem;
	}

	.download {
		float: right;
	}

	.contont {
		width: 100%;
		height: 83.92vh;
		padding-top: 2vh;
		padding-bottom: 1vh;
		overflow: hidden;

		.button {
      margin-left: 1%;
			button {
				width: 100%;
				height: 4.5vh;
				font-size: 100%;
				border-radius: 7px;
				border-color: #FFFFFF;
			}
		}

.el-cascader__tags {
    flex-wrap: nowrap;
    overflow: hidden;
}
		.active {
			color: #ffffff !important;
			background-color: #1ac7b6 !important;
			border-color: #1ac7b6 !important;
		}
    .el-select__tags {
    flex-wrap: nowrap;
    overflow: hidden;
    }
    .el-tag {
        background-color: #ecf5ff;
        border-color: #d9ecff;
        display: inline-block;
        height: 32px;
        padding: 0 10px;
        line-height: 30px;
        font-size: 14px;
        color: #409EFF;
        border-width: 1px;
        border-style: solid;
        border-radius: 4px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        white-space: nowrap;
    }
		.dropdown {
			width: 100%;
			margin-left: 5%;
			line-height: 5vh;
			text-align: center;

			input {
				height: 5vh;
				font-size: 14px;
				line-height: 5vh;
				text-align: center;
			}
		}

		.el-range-editor--small .el-range-separator {
			line-height: 4vh;
			font-size: 16px;
		}

		.datePicker {
			margin-left: 5%;
			width: 140%;
			height: 5vh;

			input {
				line-height: 10vh;
				font-size: 15px;
				// height: 5vh;
				text-align: center;
			}
		}

		.spans {
			display: inline-block;
			width: 80%;
			text-align: center;
			height: 4vh;
			line-height: 4vh;
			margin-top: 0.75vh;
			margin-left: 12vh;
			border-radius: 7px;
			background-color: #ffffff;
			color: #8c8c8c;

			.el-icon-picture {
				color: #196dff;
				margin-right: 5px;
			}

			.el-icon-s-marketing {
				color: #207245;
				margin-right: 5px;
			}
		}
	}
</style>
